package pojo;

import java.io.BufferedReader;
import java.util.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Consumer;

public class UserInformation {
    Map<String, Set<String>> map;
    Path file;

    public UserInformation() {
    }

    public UserInformation(Path file) {
        this.file = file;
        this.map=new HashMap<>();
        FileToMap();
    }

    public Map<String, Set<String>> getMap() {
        return map;
    }

    public Path getFile() {
        return file;
    }

    /**
     * 将Map写入到file文件中。默认Map<String A,String A'>
     * file中以A=A来表示，Map中每个键值对显示一行
     * @throws IOException
     */
    private void MapToFile(Map<String, Set<String>> map,Path file) throws IOException{
        StringBuffer buffer = new StringBuffer();
        for(String string:map.keySet()){
            String key = string;
            Set<String> value = map.get(string);
            buffer.append(key + "=");
            value.iterator().forEachRemaining(new Consumer<String>() {
                @Override
                public void accept(String s) {
                    buffer.append(s+',');
                }
            });
            buffer.append('\n');
        }
        Path path = Files.writeString(file, buffer);
    }

    /**
     * 将文件读取转换成Map
     * @return
     */
    private void FileToMap() {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader( Files.newBufferedReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                if (!tempString.startsWith("\n")) {
                    String[] strArray = tempString.substring(10).split(",");
                    Set<String> set=new HashSet<>();
                    set.addAll(Arrays.asList(strArray));
                    map.put(tempString.substring(0,9).trim(), set);
                }
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }
}
